package services.application;

import dto.app.*;
import models.application.*;
import models.pubobj.*;
import models.user.*;
import play.Logger;
import play.db.ebean.Transactional;
import services.exception.*;
import utils.*;

import java.util.*;

public class AniAppRegisterService extends AniAppService{
    @Transactional
    public static void registerApp(Map<String, String> appRegInfoArgs, AniUser curUser){

        //verify required
        MVCUtils.verifyRequiredElements(appRegInfoArgs, UploadAppInfoDto.requiredRegisterFieldKeys);
        //check url
        UploadAppInfoDto oneAppInfo = new UploadAppInfoDto(appRegInfoArgs, curUser);
        AniApp oneAppDao = oneAppInfo.getAniAppDao();
        AniAppService.checkAppForwardUrlLegality(oneAppDao);
        //check duplicate app name
        checkAppNotExistence(oneAppDao);
        //check rely on app privacy(if private, self only; else must be one user's)
        checkRelyOnAppPrivacy(
                curUser,
                AniApp.findByAppId(
                        oneAppInfo.relyOnAppId
                )
        );
        saveAppInfo(oneAppInfo);
    }

    // -- Transmission with DB
    private static void saveAppInfo(UploadAppInfoDto oneApp){
        try{
            AniObjectState oneState = AniObjectState.findByStateKey(AniObjectState.States.DISABLED.name());
            oneApp.getAniAppDao(oneState, generateAppToken()).save();
        }catch(Exception e){
            String message = "APP_REGISTER_FAILED";
            Logger.error(message);
            throw new AniDataException(message);
        }
    }
    private static String generateAppToken(){
        return SecureUtils.generateMD5String(String.valueOf(SecureUtils.generateRandomUniqueId()));
    }
}